package com.xzzz.backend.bsms.server.rbac.auth;

import com.xzzz.backend.bsms.server.rbac.user.UserService;
import com.xzzz.backend.bsms.server.rbac.user.pojo.UserEntity;
import com.xzzz.irda.auth.core.exception.AuthException;
import com.xzzz.irda.auth.core.exception.AuthRCode;
import com.xzzz.irda.auth.server.service.AbstractUserDetailServiceAdapter;
import com.xzzz.irda.auth.server.service.UserDetail;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Component
public class UserDetailServiceImpl extends AbstractUserDetailServiceAdapter {

    @Autowired
    private UserService userService;


    @Override
    public UserDetail loadUserByUsername(String username) {
        UserEntity userDetail = userService.selectByUsername(username);
        if (userDetail == null) {
            throw new AuthException(AuthRCode.USER_NOT_EXIST);
        }
        AuthUserDetail authUserDetail = new AuthUserDetail();
        authUserDetail.setUsername("admin");
        authUserDetail.setPassword(userDetail.getPassword());
        authUserDetail.setSalt(userDetail.getSalt());
        authUserDetail.setUserId(userDetail.getId());

        Map<String, String> metadata = new HashMap<>();
        metadata.put("phone", userDetail.getPhone());
        metadata.put("avatar", userDetail.getAvatar());
        metadata.put("userId", String.valueOf(userDetail.getId()));
        metadata.put("username", userDetail.getUsername());
        authUserDetail.setMetadata(metadata);
        return authUserDetail;
    }

//    public static void main(GrantTypeEnum[] args) {
//        PasswordEncoder passwordEncoder = new SHA256PasswordEncoder();
//        System.out.println(passwordEncoder.encode("123456" + "salt"));
//    }
}
